package cn.tedu.springbootdemo;

import cn.tedu.springbootdemo.controller.UserController;
import cn.tedu.springbootdemo.entity.User;
import cn.tedu.springbootdemo.service.UserService;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.test.web.servlet.MockMvc;

import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

/**
 * @WebMvcTest 可以对Web层进行分片测试
 *  只测试控制器，其他的组件一概不测试
 * @WebMvcTests 会自动的将UserService注入给UserController
 *
 */
@WebMvcTest(UserController.class)
public class WebMvcTestDemo {

    @Autowired MockMvc mockMvc;

    @MockBean UserService userService;

    @BeforeEach
    void init(){
        //训练userService中的login方法
        Mockito.when(userService.login("tom","1234"))
            .thenReturn(new User(1,"tom","1234","ADMIN"));
    }

    //进行login的分片测试
    @Test
    void login() throws Exception {
        mockMvc.perform(get("/users/login") //发起请求
            .param("username", "tom")    //传递第一个参数
            .param("pwd","1234"))        //传递第二个参数
            .andExpect(content().string("登录成功！")) //期望获取响应结果的内容
            .andExpect(status().isOk());
        System.out.println("Login ok");
    }
}
